intervals = [[1,3],[2,6],[8,10],[15,18]]

def merge_intervals(intervals):
    if len(intervals) <= 1:
        return intervals

    _sorted = sorted(intervals, key=(lambda l: l[0]))
    res = [_sorted[0]]
    for i in range(1, len(_sorted)):
        cur = _sorted[i]
        pre = res[-1]
        if cur[0] <= pre[1]:
            merged = [pre[0], cur[1]]
            res[-1] = merged
        else:
            res.append(cur)
    return res

print(merge_intervals(intervals))
print(merge_intervals([[1,4],[4,5]]))